package com.fmboy.MXH.nav.service.impl;

import com.fmboy.MXH.nav.domain.entities.FileResponse;
import com.fmboy.MXH.nav.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileService {

    @Value("${file.uploadPath}") // 静态资源访问路径
    private String uploadPath;
    @Value("${file.upload-dir}") // 文件上传目录
    private String uploadDir;
    @Value("${file.serverIp}")
    private String serverIp;

    public List<FileResponse> uploadFiles(MultipartFile[] files, HttpServletRequest request) throws IOException {
        // 获取用户ID
        String userId = String.valueOf(UserContext.getUserId());
        // 创建用户上传目录
        String userUploadDir = Paths.get(uploadDir, userId).toString();

        File directory = new File(userUploadDir);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录
            log.info("创建用户上传目录: {}", userUploadDir);
        }

        List<FileResponse> fileResponses = new ArrayList<>();

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                log.warn("上传一个空文件。");
                return fileResponses;
            }

            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                log.warn("文件没有名称。");
                return fileResponses;
            }

            try {
                byte[] bytes = file.getBytes();
                String uniqueFileName = UUID.randomUUID() + "_" + sanitizeFileName(originalFilename);
                Path path = Paths.get(userUploadDir, uniqueFileName);
                Files.write(path, bytes);

//                String fileUrl = request.getScheme() + "://" + serverIp + ":" + request.getServerPort() + uploadPath + userId + "/" + uniqueFileName;
                String fileUrl = uploadPath + userId + "/" + uniqueFileName;
                fileResponses.add(new FileResponse(originalFilename, fileUrl, file.getSize()));
                log.info("文件上传成功: {}", uniqueFileName);
            } catch (IOException e) {
                log.error("上传文件失败: {}", e.getMessage(), e);
                throw new IOException("上传文件失败", e);
            }
        }
        return fileResponses;
    }

    // 去除文件名中的特殊字符
    private String sanitizeFileName(String filename) {
        return filename.replaceAll("[^a-zA-Z0-9._-]", "_");
    }

    // 提取文件扩展名
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1).toLowerCase();
    }
}
